package com.gec.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

@Controller
public class BaseController {
    protected final String JSON = "text/json;charset=utf-8";
    protected final String HTML = "text/html;charset=utf-8";
    public void prt(String result) {
        System.out.println("{BaseHHHHHHHH}" + result);
    }

    protected <T> T getBean(HttpServletRequest req, Class<T> clazz) {
        // {1}获取所有参数【key-val】。
        Map<String, String[]> map = req.getParameterMap();
        Set<String> fldNames = map.keySet();
        T t;
        prt("getBean[clazz]:" + clazz);
        try {
            t = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e1) {
            e1.printStackTrace();
            throw new RuntimeException("创建 " + clazz.getSimpleName() + " 对象失败。");
        }
        for (String fName : fldNames) {
            Field F;
            String mtdName;
            try {

                F = clazz.getDeclaredField(fName);
                prt("F:" + F);
                // 把 username ---> setUsername
                mtdName = getMtdName(fName);
                Method M = clazz.getDeclaredMethod(mtdName, F.getType());
                // {2}获取参数数组第 0 号元素。
                String _val = map.get(fName)[0];
                prt("getBean[_val]" + _val);
                // {3}调用 user.setUsername();
                M.invoke(t, getVal(F.getType(), _val));
            } catch (NoSuchFieldException | NoSuchMethodException e) {
                // {ps}没有方法没有必要处理。
                // e.printStackTrace();
                prt("没有这个字段:" + fName);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
                throw new RuntimeException("妈的,输入数字啊,操");
            }
        }
        return t;
    }

    private Object getVal(Class type, String _val) {
        if (type == String.class) {
            return _val;
        } else if (type == int.class || type == Integer.class) {
            return Integer.valueOf(_val);
        } else if (type == double.class || type == Double.class) {
            return Double.valueOf(_val);
        } else if (type == float.class || type == Float.class) {
            return Float.valueOf(_val);
        }
        return null;
    }

    private String getMtdName(String fName) {
        String first = fName.substring(0, 1);
        first = first.toUpperCase();
        return "set" + first + fName.substring(1);
    }


    protected String makeURLMsg(String msg) {
        String _msg = null;
        try {
            _msg = URLEncoder.encode(msg, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return _msg;
    }


    protected String sendError(String cause) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("result", "failed");
        jsonObj.put("cause", cause);
        jsonObj.put("status", -1);
        return jsonObj.toString();
    }

    // {2}sendData 方法
    protected String sendData(Object obj) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("result", "success");
        jsonObj.put("data", obj);
        jsonObj.put("status", 200);
        return jsonObj.toString();
    }

    // {3}sendSuccess 方法
    protected String sendSuccess() {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("result", "success");
        jsonObj.put("status", 200);
        jsonObj.put("msg", "");
        return jsonObj.toString();
    }
    protected String sendFailed(Exception e) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("result", "error");
        jsonObj.put("status", 500);
        jsonObj.put("cause", e.getMessage());
        return jsonObj.toString();
    }
}
